package com.xulinhao.web;/**
 * @author xulinhao
 * @create 2021-05-28 21:13
 */

import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.gson.Gson;
import com.xulinhao.service.UserService;
import com.xulinhao.service.impl.UserServiceImpl;
import com.xulinhao.pojo.User;
import com.xulinhao.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @Author xlh
 * @packagename: com.xulinhao.web
 * @classname: UserServlet
 * @Description:
 * @Date 2021/5/28
 */
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的参数 username
        String username = req.getParameter("username");
        // 调用 userService.existsUsername();
        boolean existsUsername = userService.existsUsername(username);
        // 把返回的结果封装成为 map 对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("existsUsername",existsUsername);
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }


    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
//        String email = req.getParameter("email");
        //获取Session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        String code = req.getParameter("code");

        User user = WebUtils.copyParamToBean(req.getParameterMap(),new User());

        //2 检查验证码是否正确 === 目前先要求验证码为:abcde
        if (token != null && token.equalsIgnoreCase(code)) {
            //正确
            //3 检查用户名是否可用
            if (userService.existsUsername(user.getUsername())) {
                //不可用则跳回注册页面
                System.out.println("用户名已存在!");

                //把回显信息,保存到request域中
                req.setAttribute("msg", "用户名已存在!");
                req.setAttribute("username", user.getUsername());
                req.setAttribute("email", user.getEmail());

                //跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
            } else {
                //可用则调用service保存到数据库
                userService.registUser(new User(null, user.getUsername(), user.getPassword(), user.getEmail()));
                //跳到注册成功页面regist_success.html
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            //错误,则调回注册页面
            //把回显信息,保存到request域中
            req.setAttribute("msg", "验证码错误!");
            req.setAttribute("username", user.getUsername());
            req.setAttribute("email", user.getEmail());
            System.out.println("验证码错误");
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //调用userService.login()登录处理业务
        User loginUser = userService.login(new User(null, username, password, null));
        //如果等于null,说明登录失败
        if (loginUser == null) {
            //把错误信息,和回显的表单项信息,保存到Request域中
            req.setAttribute("msg", "用户名或密码错误!");
            req.setAttribute("username", username);
            //跳回登录页面
            System.out.println("登录失败");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            //保存用户登录的信息
            req.getSession().setAttribute("user",loginUser);
            //登录成功则跳到成功页面login_success.html
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);
        }
    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session中用户登录的信息(或者销毁Session)
        req.getSession().invalidate();
        //2.重定向到首页
        resp.sendRedirect(req.getContextPath());
    }
}
